/*
 * @Author: zhangyujie
 * @Date:   2015-08-12 10:42:41
 * @Last Modified by:   zhangyujie
 * @Last Modified time: 2015-08-14 14:06:41
 */

'use strict';

(function() {

	var Y = window.Y || {}


	var util = {

		getNumByRate: function(w, rate) {

			if (typeof rate === 'string' && rate.indexOf('%')) {

				return w * Number(rate.replace('%', '')) / 100
			} else if (typeof rate === 'string' && rate.indexOf('px')) {

				return Number(rate.replace('px', ''))
			} else {

				return Number(rafte)
			}
		},
		getTextSize: function(text, style) {

			var span, position, width, height

			span = document.createElement('span')

			span.innerText = text

			for (var key in style) {

				span.style[key] = style[key]
			}

			document.body.appendChild(span)

			position = span.getBoundingClientRect()

			width = position.width

			height = position.height

			document.body.removeChild(span)

			return {

				width: width,
				height: height
			}
		}
	}

	Y.two_1 = function(setting) {


		var width, height, selector,
			colorset, dom, position,
			name, value, i, serie,
			data, min, max, xScale,
			yScale, xScaleData, margin,
			contentW, contentH, xAxis, yAxis,
			valueLine, linearGradient, event, line,
			hightCircle, lowCircle

		var svg, content, left, right, ticks,
			lineWrap


		selector = setting.selector
		dom = document.querySelector(selector)
		position = dom.getBoundingClientRect()
		width = position.width
		height = position.height
		colorset = setting.colorset
		data = setting['series']
		margin = setting['margin']

		contentW = width - margin.left - margin.right
		contentH = height - margin.top - margin.bottom


		min = d3.min(data, function(d, i) {

			return d3.min(d.value)
		})
		max = d3.max(data, function(d, i) {


			return d3.max(d.value)
		})
		max = Math.ceil(max / 100) * 100


		xScaleData = []

		data.forEach(function(d, i) {

			xScaleData.push(d.name)
		})

		xScale = d3.scale.ordinal()
			.domain(xScaleData)
			.rangeBands([0, contentW], 0)

		xAxis = d3.svg.axis()
			.scale(xScale)
			.orient('bottom')
			.tickValues(xScaleData)
			.tickSize(-contentH)

		svg = d3.select(selector)
			.append('svg')
			.attr('width', width)
			.attr('height', height)
		svg.append('g')
			.attr('class', 'axis')
			.classed('xAxis', true)
			.attr('transform', 'translate(' + margin.left + ',' + (margin.top + contentH) + ')')
			.call(xAxis)

		svg.append('g')
			.attr('class', 'axis')
			.classed('xAxis', true)
			.classed('hidden', true)
			.attr('transform', 'translate(' + margin.left + ',' + (margin.top) + ')')
			.call(xAxis.tickSize(0).tickValues(null))

		svg.selectAll('.xAxis line')
			.attr('transform', 'translate(' + xScale.rangeBand() / 2 + ',0)')

		yScale = d3.scale.linear()
			.domain([max, 0])
			.range([0, contentH])

		yAxis = d3.svg.axis()
			.scale(yScale)
			.orient('right')
			.tickSize(0)
		svg.append('g')
			.attr('class', 'axis')
			.classed('yAxis', true)
			.attr('transform', 'translate(' + (margin.left + contentW) + ',' + margin.top + ')')
			.call(yAxis)

		content = svg.append('g')
			.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')')

		linearGradient = content.append('defs')
			.append('linearGradient')
			.attr('id', 'mylinearGradient')
			.attr('x1', '0%')
			.attr('y1', ' 0%')
			.attr('x2', '0%')
			.attr('y2', '100%')

		linearGradient.append('stop')
			.attr('offset', '50%')
			.attr('stop-color', setting.rectStyle.fill)
			.attr('stop-opacity', '1')

		linearGradient.append('stop')
			.attr('offset', '100%')
			.attr('stop-color', '#fff')
			.attr('stop-opacity', '1')
		content.append('g').selectAll('rect')
			.data(data)
			.enter()
			.append('rect')
			.attr('x', function(d, i) {

				return xScale(d.name)
			})
			.attr('y', function(d, i) {
				return yScale(d.value[0])
			})
			.attr('width', 0)
			.attr('height', function(d, i) {

				return contentH - yScale(d.value[0])
			})
			.style(setting.rectStyle)
			.style('fill', 'url(#mylinearGradient)')
			.transition()
			.duration(2000)
			.attr('width', xScale.rangeBand())

		valueLine = d3.svg.line()
			.interpolate('linear')
			.x(function(d) {

				return xScale(d.name) + xScale.rangeBand() / 2
			})
			.y(function(d) {

				return yScale(d.value[1])
			})

		content.append('g')
			.append('path')
			.attr('d', valueLine(data))
			.style(setting.pathStyle)
			.call(end)

		lineWrap = content.append('g')
			.style('display', 'none')
		line = lineWrap.append('line')
			.attr('x1', 0)
			.attr('y1', 0)
			.attr('x2', 0)
			.attr('y2', contentH)
			.style(setting.pathStyle)


		lowCircle = lineWrap.append('circle')
			.attr('r', 6)
			.attr('fill', setting.rectStyle.fill)
			.attr('stroke-width', '2px')
			.attr('stroke', '#fff')
		hightCircle = lineWrap.append('g')

		hightCircle.append('circle')
			.attr('r', 10)
			.attr('fill', '#fff')
			.attr('stroke-width', '2px')
			.attr('stroke', setting.pathStyle.stroke)

		hightCircle.append('circle')
			.attr('r', 6)
			.attr('fill', setting.pathStyle.stroke)



		content
			.on('touchstart', touch)
			.on('touchmove', touch)
			// .on('touchend', function(d) {
			// 	line
			// 		.style('display', 'none')
			// })


		function end(line) {
			line.transition()
				.duration(3000)
				.attrTween("stroke-dasharray", tweenDash)
				.attr('fill-opacity', 1)

		}

		function tweenDash() {
			var l = this.getTotalLength(),
				i = d3.interpolateString("0,kkk" + l, l + "," + l);
			return function(t) {
				return i(t);
			}
		}

		function touch() {

			var target = null,
				tagName, height,
				position, left, key,
				lineValue, rectValue,
				index, arr

			position = d3.mouse(dom)
			target = d3.event.target
			tagName = target.tagName

			left = position[0] - margin.left

			arr = getData(left)

			index = arr[0]

			if (index >= 0 && left >= (xScale.rangeBand() / 2) && left <= (contentW - xScale.rangeBand() / 2)) {

				lineWrap.style('display', 'block')

				line
					.attr('transform', 'translate(' + (position[0] - margin.left) + ',' + 0 + ')')

				lowCircle
					.attr('transform', 'translate(' + (position[0] - margin.left) + ',' + yScale(data[index].value[0]) + ')')

				hightCircle
					.attr('transform', 'translate(' + (position[0] - margin.left) + ',' + arr[1] + ')')
			}



		}

		function getData(num) {

			var unitData = contentW / xScaleData.length,
				preIndex,
				nextIndex, currentIndex, k,
				vaildIndex, y, currentValue, vaildValue, x, b


			var currentIndex = Math.floor(num / unitData)

			if (currentIndex < 0) {

				currentIndex = 0
			}

			if (currentIndex > xScaleData.length - 1) {

				currentIndex = xScaleData.length - 1
			}
			preIndex = currentIndex - 1

			nextIndex = currentIndex + 1

			if ((num / unitData) - currentIndex >= 0.5) {

				vaildIndex = nextIndex

			} else {

				vaildIndex = preIndex
			}

			if (vaildIndex <= -1 || vaildIndex >= xScaleData.length - 1) {

				vaildIndex = currentIndex
			}

			currentValue = yScale(data[currentIndex].value[1])

			vaildValue = yScale(data[vaildIndex].value[1])

			if (currentIndex >= vaildIndex) {

				x = num - (currentIndex * unitData) + xScale.rangeBand() / 2

				k = -1

				b = vaildValue
			} else {

				x = num - (currentIndex * unitData) - xScale.rangeBand() / 2


				k = 1

				b = currentValue
			}
			y = k * (vaildValue - currentValue) * x / unitData + b

			return [currentIndex, y]
		}


	}


	window.Y = Y
}())